<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/1
 * Time: 15:41
 */
namespace  app\blogadmin\model;

use think\Db;
use think\Model;
use think\Request;


class Category extends Model{
    protected $_table='category';

    /**
     * 添加数据
     * @param $data
     * @return bool
     */
    public function add($data){
        $res=Db::table($this->_table)->insert($data);
        if($res){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 根据id 删除数据
     * @param $id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del($id){
        $res=Db::table($this->_table)->delete($id);
        if($res){
            return true;
        }else{
            return false;
        }
    }

    public function upda($data){
        $res=Db::table($this->_table)->update($data);
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
     public function cateTree(){
            $data=Db::table($this->_table)->select();
            return $this->loop($data);
     }

     public function loop($data,$pid=0,$level=0){
         static $arr=[];
         foreach ($data as $key=>$vo){
             if($vo['pid']==$pid){
                 $vo['level']=$level;
                 $arr[]=$vo;
                 $this->loop($data,$vo['id'],$level+1);
             }
         }
         return $arr;
     }

     public function getAllIds($id){
         //获取所有的栏目信息
         $data=$this->select();
         $ids=$this->getIds($data,$id);
         $ids[]=$id;
         return $ids;
     }

     protected function getIds($data,$id){
         static $arr=[];
         foreach ($data as $k=>$v){
             if($v['pid']==$id){
                 $arr[]=$v['id'];
                 $this->getIds($data,$v['id']);
             }
         }
         return $arr;
     }







}